from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
from app01.models import TieZi
from app01.models import ReplyTieZi
from app01.utils.form import AddTieZi


# Create your views here.


def tiezi_show(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        show_tiezi = TieZi.objects.all()
        return render(request, "tiezi/tiezi_show.html", {"show_tiezi": show_tiezi, 'coo': coo})


def tiezi_read(request, id):
    coo = request.session.get('info', "")
    read_tiezi = TieZi.objects.filter(id=id).first()
    tiezireply = ReplyTieZi.objects.filter(tiezi_id_id=id)
    mainreeply = tiezireply & ReplyTieZi.objects.filter(replytiezi_id__isnull=False)  # 子评论
    manreply = tiezireply & ReplyTieZi.objects.filter(reply_reply_id__isnull=True)  # 主评论
    dic = {}
    for obj in manreply:
        reply = mainreeply & ReplyTieZi.objects.filter(reply_reply_id=obj.id).order_by("release_time")
        lis = []
        for i in reply:
            if i.user_id is not None:
                lis.append((i.user_id.name,
                            (tiezireply & ReplyTieZi.objects.filter(id=i.replytiezi_id)).first().user_id.name,
                            i.content))
            else:
                continue
        dic[obj] = lis
    return render(request, "tiezi/tiezi_read.html", {"coo": coo, "read_tiezi": read_tiezi, "dic": dic})


def tiezi_add(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        form = AddTieZi()
        return render(request, "tiezi/tiezi_add.html", {'coo': coo, 'form': form})

    form = AddTieZi(data=request.POST)
    if form.is_valid():
        form.instance.user_id_id = request.session["info"]["id"]
        form.instance.release_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        form.instance.bankuai_id_id = 1
        form.save()
        return redirect("/tiezi/")


def tiezi_edit(request, id):
    coo = request.session.get('info', "")
    row_object = TieZi.objects.filter(id=id).first()
    if request.method == 'GET':
        form = AddTieZi(instance=row_object)
        return render(request, "tiezi/tiezi_edit.html", {"form": form, 'coo': coo})
    form = AddTieZi(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/me/fabu/tiezi/")


def tiezi_delete(request):
    uid = request.GET.get('uid')
    exists = TieZi.objects.filter(id=uid).exists()
    if not exists:
        return TieZi({"status": False, 'error': "删除失败，数据不存在。"})

    TieZi.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


@csrf_exempt
def pl(request):
    coo = request.session.get('info', "")
    data = request.POST
    tiezi_id = data.get("tiezi_id", "")
    content = data.get('content', "")
    if tiezi_id == "" or content == "":
        return JsonResponse({"status": False, "error": "不可为空"})
    ReplyTieZi.objects.create(tiezi_id_id=tiezi_id,user_id_id=coo["id"] , content=content, release_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    reply_count = TieZi.objects.filter(id=tiezi_id).first().reply_count + 1
    TieZi.objects.filter(id=tiezi_id).update(reply_count=reply_count)
    return JsonResponse({"status": True})
